package com.xm2.demo.system.center.service;

import com.xm2.demo.model.Center;
import com.xm2.demo.system.center.dao.CentersRepository;
import com.xm2.demo.system.center.dto.CenterInfo;
import com.xm2.demo.system.center.dto.CenterPage;
import com.xm2.demo.system.shop.dao.StoresRepository;
import com.xm2.demo.utils.Pagination;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;

import java.util.List;

/**
 * @Create
 * @create 2018-12-12 14:54
 * @Description：
 */
@Service
public class CenterServiceImpl implements CenterService {

    @Autowired
    private CentersRepository centersRepository;

    @Autowired
    private StoresRepository storesRepository;

    @Override
    public Pagination findByPageable(Pagination pagination) {
        pagination.setTotalRows(centersRepository.findAllCount().size());
        pagination.setList(centersRepository.findAllById(pagination.getStartRow(), pagination.getSize()));
        return pagination;
    }

    @Override
    public void addCenter(CenterInfo centerInfo) {
        Center center = new Center();
        if (centerInfo.getId() == null) {
            center.setCenterName(centerInfo.getCenterName());
            center.setCenterAddress(centerInfo.getCenterAddress());
            centersRepository.save(center);
        } else {
            BeanUtils.copyProperties(centerInfo, center);
            centersRepository.save(center);
        }

    }

    @Override
    public void deleteByIds(String ids) {
        // 接收包含stuId的字符串，并将它分割成字符串数组
        String[] stuList = ids.split(",");
        // 将字符串数组转为List<Intger> 类型
        List<Integer> LString = new ArrayList<Integer>();

        Center center = centersRepository.findOne(0);
        if (center == null) {
            center.setId(0);
            center.setCenterName("未绑定");
            center.setCenterAddress("未绑定");
            centersRepository.save(center);
        }
        for (String str : stuList) {
            LString.add(new Integer(str));
            //修改门店中心id 为0
            storesRepository.updateCenterId(new Integer(str));
        }
        //删除
        centersRepository.deleteCenterByIdIn(LString);
    }

    @Override
    public List<Center> findAll() {
        return centersRepository.findAllCount();
    }

    @Override
    public Pagination findByCenterName(CenterPage centerPage) {
        centerPage.setTotalRows(centersRepository.findByCenterNameCount(centerPage.getCenterName()));
        centerPage.setList(centersRepository.findLikeByCenterName(centerPage.getCenterName()));
        return centerPage;
    }
}
